package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user){
        String verifyCode = "1234";
        System.err.println("本次生成的验证码："+verifyCode);

        // session过期时间30分钟，不适合用在验证码处
//        session.setAttribute("verifyCode"+user.getPhone(),verifyCode);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("verifyCode"+user.getPhone(),verifyCode,1, TimeUnit.MINUTES); // 设置1分钟后失效
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> param,HttpSession session){
        String phone = param.get("phone");
        String code = param.get("code"); // 用户输入
        // 取出session中的验证码
//        String verifyCode = (String) session.getAttribute("verifyCode"+phone); // 系统生成的
        // 从redis取出验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String verifyCode = (String) valueOperations.get("verifyCode" + phone);

        // 交给service去校验
        User user = userService.login(phone,code,verifyCode);
        if (user!=null){
            // 登录成功在session中做一个登陆标记
            session.setAttribute("user",user.getId());
            redisTemplate.delete("verifyCode" + phone);
        }
        return R.success("登陆成功！");
    }
}
